import cv2, glob
import numpy as np
import os

import matplotlib.pyplot as plt
import pylab
# 输出图像的眼球半径都为1*scale个像素
import numpy as np
import cv2


# img = np.zeros((200,200,3),dtype=np.uint8)
# cv2.circle(img,(60.0,60.0),30.0,(0,0,255),shift=1)
# cv2.imshow('img',img)
# import matplotlib.pyplot as plt
# plt.plot([3,3,2,3,3,5,6])
# plt.show()
# def scaleRadius(img,scale):
#     x = img[int(img.shape[0]/2),:,:].sum(1) # 图像中间1行的像素的3个通道求和。输出（width*1）
#     r = (x>x.mean()/10).sum()/2 # x均值/10的像素是为眼球，计算半径
#     s = scale*1.0/r
#     return cv2.resize(img,(0,0),fx=s,fy=s)
#     # 输出长宽 为 原长宽*scale/r = （原长宽/r）*scale。
#     # 那么，输出图像的眼球半径都为1*scale个像素。
#
# scale = 300
# # for f in glob.glob ("train/∗. jpeg")+ glob . glob ("test/∗.jpeg"):
# def circle_crop(f):
# 	# try :
#     a=cv2.imread(f)
#     #scale img to a given radius
#     a=scaleRadius(a, scale)
#     #subtract local mean color
#     a=cv2.addWeighted(a,4,cv2.GaussianBlur(a,(0,0),scale/30),-4,128)
#     #remove out er 10%
#     b = np.zeros(a.shape)
#     print(a.shape[1]/2,a.shape[0]/2,scale * 0.9)
#     cv2.circle(b,(a.shape[1]/2, a.shape[0]/2), int(scale * 0.9),(1, 1, 1), -1)
#     a = a*b+128*(1-b)
#     print(a.shape,np.max(a))
# #     a = a/255.
# #     plt.imshow(a)
# #     plt.show()
#
#     cv2.imwrite('/media/chh/disk6T/DR/kaggle/1.jpeg', a)
# 	# except:
# 	# 	print(f)
# path = '/media/chh/disk6T/DR/kaggle/train/8387_right.jpeg'
# pitcher = circle_crop(path)

# path = '/media/chh/disk6T/DR/kaggle/train/0a61bddab956.png'
def crop_image_from_gray(img, tol=7):
    if img.ndim == 2:
        mask = img > tol
        return img[np.ix_(mask.any(1), mask.any(0))]
    elif img.ndim == 3:
        # 先将图片转换成灰度
        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # 设置遮罩，255为纯白色， 0为纯黑色
        # 其实这个mask是过滤掉一些黑色像素
        mask = gray_img > tol

        # np.ix_([a1,a2,a3,...],[b1,b2,b3,...]): 讲一个数组 1、选取其中的a1,a2,a3列， 然后将每列元素以b1,b2,b3方式重新排列
        check_shape = img[:, :, 0][np.ix_(mask.any(1), mask.any(0))].shape[0]
        if (check_shape == 0):  # image is too dark so that we crop out everything,
            return img  # return original image
        else:
            img1 = img[:, :, 0][np.ix_(mask.any(1), mask.any(0))]
            img2 = img[:, :, 1][np.ix_(mask.any(1), mask.any(0))]
            img3 = img[:, :, 2][np.ix_(mask.any(1), mask.any(0))]
            #         print(img1.shape,img2.shape,img3.shape)
            img = np.stack([img1, img2, img3], axis=-1)
        #         print(img.shape)
        return img


def circle_crop(img, sigmaX=30):
    """
    Create circular crop around image centre
    """

    img = cv2.imread(img)
    img = crop_image_from_gray(img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    height, width, depth = img.shape

    x = int(width / 2)
    y = int(height / 2)
    r = np.amin((x, y))

    circle_img = np.zeros((height, width), np.uint8)
    cv2.circle(circle_img, (x, y), int(r), 1, thickness=-1)
    # bitwise_and 来裁剪原始图像，得到一个圆形图像
    img = cv2.bitwise_and(img, img, mask=circle_img)
    img = crop_image_from_gray(img)
    img = cv2.addWeighted(img, 4, cv2.GaussianBlur(img, (0, 0), sigmaX), -4, 128)
    # print(img.shape)

    return img


path1 = '/home/lsy/PycharmProjects/DR/train/'
savepath = '/home/lsy/PycharmProjects/DR/save/'
path1dir = os.listdir(path1)
for name in path1dir:
    path2 = os.path.join(path1, name)
    # print(path2)
    a = circle_crop(path2)
    path3 = os.path.join(savepath, path2.split('/')[-1])
    print(path3)
    cv2.imwrite(path3, a)
